<template>
  <div>
    <!--工具栏-->
    <div class="tool-bar">
      <div class="tool-bar-left">
        <Upload
            action="#"
            :before-upload="handleUpload"
            multiple
            :max-size="10485760">
          <Button type="primary" v-preventReClick v-perms="['file/upload']">本地上传</Button>
        </Upload>
        <Button type="default" v-preventReClick :disabled="selectedIds.length===0" @click="handleDelete"
                v-perms="['file/del']">删除
        </Button>
        <Button type="default" v-preventReClick :disabled="selectedIds.length===0" @click="handleClassify"
                v-perms="['file/classify']">归类
        </Button>
      </div>
      <Space class="tool-bar-right">
        <!--搜索框-->
        <Input search enter-button placeholder="请输入名称" v-model="where.filename" @on-search="getFileLists"
               v-perms="['file/lists']"/>
        <!--<RadioGroup type="button" v-model="previewType" button-style="solid">
          <Radio label="list" style="padding: 0 4px">
            <Icon type="md-menu" size="28"/>
          </Radio>
          <Radio label="tile" style="padding: 0 4px">
            <Icon type="md-apps" size="28"/>
          </Radio>
        </RadioGroup>-->
      </Space>
    </div>
    <!--文件预览-->
    <div class="file-previewer">
      <!--列表-->
      <div class="list" v-if="previewType==='list'">
        <div style="height: 500px">
          <!--表格主题-->
          <vxe-table
              ref="fileTableRef"
              align="center"
              border
              :column-config="{resize:true}"
              :row-config="{isCurrent:true,keyField:'id'}"
              :checkbox-config="{reserve:true}"
              :data="fileTableData"
              @checkbox-change="changeBoxOne"
              @checkbox-all="changeBoxMultiple"
              height="100%">
            <vxe-column type="checkbox" width="60"/>
            <vxe-column field="id" title="ID" width="80"/>
            <vxe-column field="filename" title="名称"/>
            <vxe-column field="upload_time" title="上传时间"/>
            <vxe-column title="操作" width="200">
              <template #default="{row}">
                <Tag color="#2db7f5" size="medium" style="cursor:pointer;" @click="handleRenameFile(row)"
                     v-preventReClick v-perms="['file/rename']">重命名
                </Tag>
                <Tag color="primary" size="medium" style="cursor:pointer" @click="handleFileSee(row)" v-preventReClick
                     v-perms="['file/detail']">
                  查看
                </Tag>
                <Tag color="error" size="medium" style="cursor:pointer;" @click="handleDelete(row)"
                     v-preventReClick v-perms="['file/del']">删除
                </Tag>
              </template>
            </vxe-column>
          </vxe-table>
          <vxe-pager
              align="right"
              size="medium"
              v-model:current-page="page.currentPage"
              v-model:page-size="page.pageSize"
              :total="page.totalResult"
              @page-change="handlePageChange">
          </vxe-pager>
        </div>
      </div>
      <!--平铺-->
      <!--<div class="tile" v-if="previewType==='tile'">-->
      <!--  -->
      <!--</div>-->
    </div>
  </div>
  <Modal
      v-model="fileClassifyShow"
      title="文件归类"
      :footer-hide="true"
      width="36%">
    <FileClassify ref="fileClassifyRef" v-if="fileClassifyShow"></FileClassify>
    <div slot="footer" style="display: flex;justify-content:right;margin-top: -10px" class="btn-group">
      <Button type="default" @click="cancel" v-preventReClick>取消</Button>
      <Button type="primary" @click="classifyFile" v-preventReClick>确定</Button>
    </div>
  </Modal>

  <Modal
      v-model="renameFileShow"
      title="文件重命名"
      :footer-hide="true"
      width="36%">
    <FileRename ref="fileRenameRef" v-if="renameFileShow"></FileRename>
    <div slot="footer" style="display: flex;justify-content:right;margin-top: -10px" class="btn-group">
      <Button type="default" @click="cancelRename" v-preventReClick>取消</Button>
      <Button type="primary" @click="renameFile" v-preventReClick>确定</Button>
    </div>
  </Modal>

  <Modal
      v-model="fileSeeShow"
      title="文件预览"
      :footer-hide="true"
      fullscreen>
    <FileSee ref="fileSeeRef" v-if="fileSeeShow"/>
  </Modal>
</template>

<script setup>

import {getCurrentInstance, inject, nextTick, onMounted, reactive, ref} from "vue";
import {UploadService} from "@/api/upload";
import {FileService} from "@/api/file";
import {filterObjectArray} from "@/api/utils";
import FileClassify from "@/components/file/file-classify";
import {commonStore} from "@/store/store";
import FileRename from "@/components/file/file-rename";
import FileSee from "@/components/file/file-see";

const {proxy} = getCurrentInstance();

const previewType = ref('list');

const fileTableData = ref([]);

const reload = inject('reload');

const selectedIds = ref([]);

const where = reactive({
  filename: '',
  tid: ''
})

const page = reactive({
  currentPage: 1,
  pageSize: 10,
  totalResult: 0
});

const fileClassifyShow = ref(false)

const renameFileShow = ref(false);

const fileSeeShow = ref(false);

const handleUpload = (file) => {
  // console.log(file)
  let param = {
    file: file,
    tid: where.tid
  };
  uploadFile(param);
  return false;
}

const uploadFile = async (file) => {
  const {data} = await UploadService.UploadFile(file)
  if (data.code === 200) {
    proxy.$Message.success({
      content: data.data.msg,
      duration: 1.5,
      onClose: () => {
        reload();
      }
    })
  } else {
    proxy.$Message.error({
      content: data.data,
      duration: 1.5,
      onClose: () => {
        Promise.reject()
      }
    })
  }
}

const handleClassify = async () => {
  const getSelectedData = proxy.$refs.fileTableRef.getCheckboxRecords();
  const getSelectedId = filterObjectArray(getSelectedData, 'id');
  if (getSelectedId.length === 0) {
    proxy.$Message.warning({
      content: '请至少选择一项',
      duration: 1.5,
      onClose: () => {
        reload();
      }
    })
  } else {
    fileClassifyShow.value = true;
    await nextTick();
    proxy.$refs.fileClassifyRef.fileTypeDatum = commonStore().fileTypeDatum;
    proxy.$refs.fileClassifyRef.tid = where.tid;
    proxy.$refs.fileClassifyRef.ids = getSelectedId;
  }
}

const setFileTypeId = (e) => {
  e = e === -1 ? '' : e
  where.tid = e
  getFileLists();
}

const getFileLists = async () => {
  const {data} = await FileService.GetFileLists({
    where: where,
    page: page.currentPage + ',' + page.pageSize,
  })
  if (data.code === 200) {
    fileTableData.value = data.data.lists
    page.totalResult = data.data.total
  }
  console.log(data)
}

const handlePageChange = ({currentPage, pageSize}) => {
  console.log(currentPage, pageSize)
  page.currentPage = currentPage;
  page.pageSize = pageSize;
  getFileLists();
}

const handleDelete = async (row) => {
  row.id && selectedIds.value.push(row.id);
  proxy.$Modal.confirm({
    title: '删除操作确认',
    content: '<p>确定执行删除操作?执行成功后数据将不可恢复。</p>',
    onOk: () => {
      postDeleteFile({
        ids: selectedIds.value
      });
    },
    onCancel: () => {
      return;
    }
  })
}

const postDeleteFile = async (param) => {
  const {data} = await FileService.DeleteFilesByIds(param);
  if (data.code === 200) {
    proxy.$Message.success({
      content: data.data,
      duration: 1.5,
      onClose: () => {
        reload();
      }
    })
  } else {
    proxy.$Message.error({
      content: data.data,
      duration: 1.5,
      onClose: () => {
        Promise.reject()
      }
    })
  }
}

const cancel = () => {
  fileClassifyShow.value = false;
}

const classifyFile = () => {
  proxy.$refs.fileClassifyRef.classifyFile();
}

/**
 * 表格单选
 * @param records
 */
const changeBoxOne = ({records}) => {
  handleSelectRow(records);
}

/**
 * 表格多选
 * @param records
 */
const changeBoxMultiple = ({records}) => {
  handleSelectRow(records);
}

/**
 * 处理表格选择某一行事件
 * @param current
 */
const handleSelectRow = (current = []) => {
  const table = proxy.$refs.fileTableRef;
  const reserves = table && table.getCheckboxReserveRecords();
  const result = reserves.concat(current);

  selectedIds.value = filterObjectArray(result, 'id');
}

const handleRenameFile = async (e) => {
  renameFileShow.value = true;
  // 等所有节点挂载完毕后执行方法,适用于v-if
  await nextTick();
  await proxy.$refs.fileRenameRef.getDetail(e);
  console.log(e);
}

const renameFile = () => {
  proxy.$refs.fileRenameRef.renameFile();
}

const cancelRename = () => {
  renameFileShow.value = false;
}

const handleFileSee = async (e) => {
  fileSeeShow.value = true;
  // 等所有节点挂载完毕后执行方法,适用于v-if
  await nextTick();
  await proxy.$refs.fileSeeRef.getDetail(e);
}

onMounted(() => {
  getFileLists();
})

defineExpose({
  setFileTypeId
})

</script>

<style scoped lang="less">
@import "./file-preview-container.less";
</style>
